import { ModelClass } from './models'

import rpcCreator from './rpc.js'

const odooAddonsFiles = require.context('./addons', true, /\.js$/)

const addons = odooAddonsFiles.keys().reduce((models, modulePath) => {
  // set './app.js' => 'app'
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = odooAddonsFiles(modulePath)
  models[moduleName] = value.default
  return models
}, {})

// console.log('ModelClass', addons)

export class Api {
  // constructor() {}
  constructor(params) {
    this.rpc = rpcCreator()
  }

  get_userinfo() {
    return this.rpc.get_userinfo()
  }

  env(model) {
    const model_addons = addons[model]
    const model_extend = model_addons && model_addons.extend
    const MyModelClass = model_extend ? model_extend(ModelClass) : ModelClass
    return new MyModelClass({ model, rpc: this.rpc, env: this.env })
  }
}

const api = new Api()

export default api
